package com.wjbgn.electronicnian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjbgn.electronicnian.dto.Result;
import com.wjbgn.electronicnian.entity.NianDumplingsDO;
import com.wjbgn.electronicnian.entity.NianWordsDO;
import com.wjbgn.electronicnian.enums.CommonReturnEnum;
import com.wjbgn.electronicnian.enums.DumplingsEnum;
import com.wjbgn.electronicnian.mapper.NianWordsMapper;
import com.wjbgn.electronicnian.service.NianDumplingsService;
import com.wjbgn.electronicnian.service.NianWordsService;
import com.wjbgn.electronicnian.util.DumplingsRandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Description:
 * Create Date: 2022-01-20T11:06:12.907434600
 *
 * @author weirx
 * @version 1.0
 */
@Service
public class NianWordsServiceImpl extends ServiceImpl<NianWordsMapper, NianWordsDO> implements NianWordsService {
    @Autowired
    private NianDumplingsService dumplingsService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result learnWords(NianWordsDO dtoToDo) {
        // 保存学的话
        this.save(dtoToDo);
        // 几率获取饺子，当学会的话越多，获得饺子几率越大。
        // 获取当前会了几句话
        long count = this.count(new QueryWrapper<>(new NianWordsDO(dtoToDo.getNianId())));
        // 根据会的话的数量，获取几率
        int chance = DumplingsRandomUtil.getChance(Integer.parseInt(String.valueOf(count)));
        DumplingsEnum order = DumplingsEnum.getOrder(chance);
        if (null != order) {
            // 看看当前获得的饺子是否存在，存在就增加数量，否则就新增
            List<NianDumplingsDO> nianDumplingsDOS = dumplingsService.list(new QueryWrapper<>(new NianDumplingsDO(dtoToDo.getNianId(), order.getName())));
            if (nianDumplingsDOS.size() > 0) {
                dumplingsService.updateById(new NianDumplingsDO(nianDumplingsDOS.get(0).getId(), nianDumplingsDOS.get(0).getDumplingsNum() + 1));
            } else {
                dumplingsService.save(new NianDumplingsDO(dtoToDo.getNianId(), order.getName(), order.getHungryNum(), 1));
            }
            return Result.success(CommonReturnEnum.DUMPLINGS.getCode(), CommonReturnEnum.DUMPLINGS.getName() + "【" + order.getName() + "】", null);
        }else {
            return Result.success();
        }
    }
}